package com.example.xx.controller;

import com.aliyun.oss.OSSClient;

import com.example.xx.config.RedisConfig;
import com.example.xx.pojo.TPermission;
import com.example.xx.pojo.TRole;
import com.example.xx.pojo.User;
import com.example.xx.service.UserService;
import com.example.xx.util.*;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OSSUtil ossUtil;

    @RequestMapping("/zhuce")
    public Result zhuce(@RequestBody User user) {
        int i = userService.zhuce(user);
        //int xx = userService.login(user);
        if (i == 1) {
            return new Result(Code.SAVE_OK, "注册成功");
        } else {
            return new Result(Code.SAVE_ERR, "该用户已存在");
        }
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/denglu")
    public Result denglu(@RequestBody User user) {

        User xx = userService.login(user);
        if (xx == null) {
            return new Result(Code.GET_OK, "用户不存在");
        } else {
            String encrypt = MD5Uitl.encrypt(user.getPassword());
            if (encrypt.equals(xx.getPassword())) {
                LoginUtil loginUtil = new LoginUtil();
                loginUtil.setName(user.getUsername());
                loginUtil.setPwd(encrypt);
                // 获取角色和权限 查询这个人的角色
                List<TRole> role = userService.getRole(xx.getId());
                //使用stream流 转换成字符串集合
                List<String> rolekey = role.stream().map(item -> item.getKeyword()).collect(Collectors.toList());
                // 获取权限 查询这个人的权限
                List<TPermission> permission = userService.getPermission(xx.getId());
                //使用stream流将这个人的所有权限 转换成字符串集合
                List<String> permissionkey = permission.stream().map(item -> item.getKeyword()).collect(Collectors.toList());
                // 将角色和权限添加到集合中
                List<String> quanxian = new ArrayList<>();
                quanxian.addAll(rolekey);
                quanxian.addAll(permissionkey);
                // 将角色和权限添加到loginUtil中
                loginUtil.setQuanxian(quanxian);
                // 将loginUtil添加到redis中
                redisTemplate.opsForValue().set(user.getUsername(), loginUtil);
                // 生成一个JWT的字符串
                String jwt = "";
                // 日历
                Calendar calendar = Calendar.getInstance();
                Date time = calendar.getTime();// 当前时间
                calendar.add(Calendar.HOUR, 24);// 日历往后加24小时
                Date time1 = calendar.getTime();// 24小时之后的时间
                /**
                 * 第一个参数是 加密的算法  第二个参数是密钥
                 *
                 * signWith(SignatureAlgorithm.HS256,"hxzy")
                 * setIssuedAt()  设置签发时间
                 * setExpiration() 过期时间
                 */
                JwtBuilder qqqq = Jwts.builder().setExpiration(time1).setIssuedAt(time).signWith(SignatureAlgorithm.HS256, "qqqq");
                Map map = new HashMap();
                map.put("username", user.getUsername());
                qqqq.addClaims(map);// jwt第二个部分中有一个私有信息
                // 通过JwtBuilder对象的compact这个方法来生成JWT字符串
                jwt = qqqq.compact();
                Map map1 = new HashMap();
                map1.put("jwt", jwt);
                map1.put("duixiang", loginUtil);
                map1.put("user", xx);
                return new Result(Code.GET_OK, map1, "登录成功");
            } else {
                return new Result(Code.GET_ERR, "密码错误");
            }
        }
    }

    //编辑查全部
    @RequestMapping("/cha/{id}")
    public Result cha(@PathVariable("id") Integer id) {
        User xx = userService.cha(id);
        if (xx != null) {
            return new Result(Code.GET_OK, xx, "查询成功");
        } else {
            return new Result(Code.GET_ERR, xx, "查询失败");
        }
    }

    //修改个人信息
    @RequestMapping("/xiugai")
    public Result xiugai(@RequestBody User user) {
        int xx = userService.xiugai(user);
        if (xx > 0) {
            return new Result(Code.GET_OK, "修改成功");
        } else {
            return new Result(Code.GET_ERR, "修改失败");
        }
    }

    //上传头像到阿里服务器
    @RequestMapping("/shangchuan")
    public Result upload(MultipartFile file) throws IOException {
        System.out.println(file);
        String originalFilename = file.getOriginalFilename();
        String newname = UUID.randomUUID().toString().substring(24) + "-" + originalFilename;
        OSSClient ossClient = new OSSClient(ossUtil.getUrl(), ossUtil.getId(), ossUtil.getMiyao());
        ossClient.putObject(ossUtil.getTong(), newname, file.getInputStream());
        String url1 = ossUtil.getUrl();
        String[] split = url1.split("//");
        String url = split[0] + "//" + ossUtil.getTong() + "." + split[1] + "/" + newname;
        return new Result(Code.UPDATE_OK, url, "上传成功");
    }

    //修改头像
    @RequestMapping("/xiugaiurl")
    public Result shangchuan(@RequestBody User user) {
        int i = userService.shangchaun(user);
        if (i > 0) {
            return new Result(Code.SAVE_OK, "上传成功");
        } else {
            return new Result(Code.SAVE_ERR, "上传失败");
        }
    }

    //修改密码
    @RequestMapping("/xiugaimima")
    public Result xiugaimima(@RequestBody User user) {
        System.out.println("旧密码：" + user.getOldPassword());
        System.out.println("新密码：" + user.getPassword());
        User xx = userService.cha(user.getId());
        String password = xx.getPassword();
        MD5Uitl md5Uitl = new MD5Uitl();
        String miwen = md5Uitl.encrypt(user.getOldPassword());
        if (password.equals(miwen)) {
            int i = userService.xiugaimima(user);
            if (i > 0) {
                return new Result(Code.SAVE_OK, "修改成功");
            } else {
                return new Result(Code.SAVE_ERR, "修改失败");
            }
        } else {
            return new Result(Code.SAVE_ERR, "密码错误");
        }

    }
}
